using System;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public class UI_QuestTipSlot : MonoBehaviour
{
    [SerializeField] private TextMeshProUGUI questTipText;
    [SerializeField] private Image questTipBorder;
    [SerializeField] private float fillDuration = 1f;

    private QuestData questData;
    private bool canActive = false;
    private PlayerQuestManager questManager;
    private void OnEnable()
    {
        
    }
    private void OnDisable()
    {
        questManager.OnAddQuestAmount -= UpdateQuestTipSlot;
    }
    public void SetupQuestTipSlot(QuestData questData,PlayerQuestManager questManager)
    {
        this.questManager = questManager;
        if ((this.questData != null && this.questData != questData) || (this.questData == null))
            canActive = true;
        this.questData = questData;

        questManager.OnAddQuestAmount += UpdateQuestTipSlot;

        UpdateQuestTipSlot();
    }

    public void UpdateQuestTipSlot()
    {
        if (canActive)
            StartCoroutine(QuestTipBorderFillCo());
        else
            questTipText.text = GetText();
    }

    private IEnumerator QuestTipBorderFillCo()
    {
        questTipText.text = "";
        questTipBorder.fillAmount = 0;

        float timer = 0;
        while (timer <= fillDuration)
        {
            timer += Time.deltaTime;
            questTipBorder.fillAmount = Mathf.Clamp01(Mathf.Lerp(0, 1, timer / fillDuration));
            yield return null;
        }

        canActive = false;

        questTipText.text = GetText();
    }
    private string GetText() => questData.questDataSO.questTip + GetCountText();
    private string GetCountText() => questData.questDataSO.requireAmount > 0 ? $"({questData.requireAmount}/{questData.questDataSO.requireAmount})" : "";

}
